#include "fescreenupdater_private.h"
#include "feactualdataservice.h"
#include <QWidget>

// FeScreenUpdaterTarget
FeScreenUpdaterTarget::FeScreenUpdaterTarget(QWidget *widget, const QString &property)
{
	w = widget;
	prop = property.toLatin1();
}

FeScreenUpdaterTarget::FeScreenUpdaterTarget(const FeScreenUpdaterTarget &other)
{
	w = other.w;
	prop = other.prop;
}

FeScreenUpdaterTarget::~FeScreenUpdaterTarget()
{
}

FeScreenUpdaterTarget &FeScreenUpdaterTarget::operator=(const FeScreenUpdaterTarget &other)
{
	w = other.w;
	prop = other.prop;
	return *this;
}

// FeScreenUpdater
FeScreenUpdater::FeScreenUpdater(FeActualDataService *service, QObject *parent)
: QObject(parent)
{
	s = service;
	run = false;
}

FeScreenUpdater::~FeScreenUpdater()
{
	stop();
}

void FeScreenUpdater::addBind(FeActualDataId id, QWidget *widget, const QString &property)
{
	Q_ASSERT(!run);
	Q_ASSERT(widget);

	Binding::iterator i = binding.find(id);
	if(i == binding.end())
	{
		i = binding.insert(id, QList<FeScreenUpdaterTarget>());
	}
	i.value().append(FeScreenUpdaterTarget(widget, property));
}

void FeScreenUpdater::dataChanged(FeActualDataId id, const QVariant &value)
{
	if(run)
	{
		Binding::const_iterator i = binding.find(id);
		const QList<FeScreenUpdaterTarget> &targets = i.value();
		foreach(const FeScreenUpdaterTarget &t, targets)
		{
			t.widget()->setProperty(t.property(), value);
		}
	}
}

void FeScreenUpdater::start()
{
	if(!run)
	{
		foreach(FeActualDataId id, binding.keys())
		{
			s->addDataConsumer(id, this);
		}
		run = true;
	}
}

void FeScreenUpdater::stop()
{
	if(run)
	{
		foreach(FeActualDataId id, binding.keys())
		{
			s->removeDataConsumer(id, this);
		}
		run = false;
	}
}